<template>
  <div class="product-list">
    <div class="operation-bar">
      <el-button type="primary" @click="HdialogVisible()">添加商品</el-button>
    </div>
  
    <el-table :data="list" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column label="商品图片" width="120">
        <template slot-scope="scope">
          <img :src="$base.url+scope.row.tupian.split(',')[0]" class="product-img" v-if="scope.row.tupian">
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column :prop="nameField" label="商品名称"></el-table-column>
      <el-table-column prop="jiage" label="价格" width="120">
        <template slot-scope="scope">
          ¥ {{scope.row.jiage}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next"
      :total="total">
    </el-pagination>
  
    <!-- 添加弹窗组件 -->
    <el-dialog
      title="添加商品"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item :label="nameField === 'bijibenming' ? '笔记本名称' : 
                             nameField === 'zhujimingcheng' ? '主机名称' :
                             nameField === 'zuzhuangmingcheng' ? '组装名称' : '外设名称'" 
                     prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="jiage">
          <el-input-number v-model="form.jiage" :min="0" :precision="2"></el-input-number>
        </el-form-item>
        <!-- 修改上传组件部分 -->
        <el-form-item label="商品图片" prop="tupian">
          <file-upload
            action="file/upload"
            :limit="3"
            :multiple="true"
            :fileUrls="form.tupian ? form.tupian : ''"
            @change="tupianUploadChange"
          ></file-upload>
        
        </el-form-item>
        
        
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    type: {
      type: String,
      required: true
    },
    shangjiaId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      list: [],
      page: 1,
      limit: 10,
      total: 0,
      showReason: false,
      dialogVisible: false,
      form: {
        // 根据不同类型使用不同的字段名
        [this.nameField]: '', // 动态设置名称字段
        jiage: 0,
        tupian: '',
        shangjia_id: localStorage.getItem('shangjiaId')
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        jiage: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ]
      },
      fileList: []
    }
  },
  computed: {
    nameField() {
      const fieldMap = {
        bijiben: 'bijibenming',           // 修改为后端实际字段名
        diannaozhuji: 'zhujimingcheng',   // 修改为后端实际字段名
        yingjianzuzhuang: 'zuzhuangmingcheng', // 修改为后端实际字段名
        diannaowaishe: 'waishemingcheng'  // 这个保持不变
      }
      return fieldMap[this.type]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    
    getList() {
      const storedShangjiaId = localStorage.getItem('shangjiaId')
    
      const params = {
        page: this.page,
        limit: this.limit,
        shangjia_id: storedShangjiaId
      }
     
      
      this.$http.get(`${this.type}/page`, {params}).then(({data}) => {
        if (data && data.code === 0) {
          this.list = data.data.list
          this.total = data.data.total
         
        } else {
          this.$message.error(data.msg || '获取数据失败')
        }
      })
    },
    // 添加分页方法到 methods 对象内
    handleSizeChange(val) {
      this.limit = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },

    handleAdd() {
      this.$router.push({
        path: `/${this.type}/add`,
        query: { shangjia_id: '1' }
      })
    },

    handleEdit(row) {
      this.$router.push({
        path: `/${this.type}/edit/${row.id}`,
        query: { shangjia_id: '1' }
      })
    },

    handleDelete(row) {
      this.$confirm('确认删除该商品?', '提示', {
        type: 'warning'
      }).then(() => {
        // 修改删除请求路径
        this.$http.post(`/${this.type}/delete`, {
          id: row.id,
          shangjia_id: localStorage.getItem('shangjiaId')
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        })
      })
    },
    handleClose(done) {
      this.$refs.form.resetFields()
      this.fileList = []
      done()
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    handleUploadSuccess(response, file) {  // 添加 file 参数
      print("图片===>",response)
      if(response && response.code === 0) {
        // 如果已有图片，则追加
        if(this.form.tupian) {
          this.form.tupian += ',' + response.data;
        } else {
          this.form.tupian = response.data;
        }
        
        // 更新文件列表
        this.fileList.push({
          name: file.name,
          url: this.$base.url + response.data
        });
        
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败');
      }
    },
    // 可以移除原来的 handleRemove 方法，因为 file-upload 组件会自动处理删除
    // 修改图片上传处理方法
    tupianUploadChange(fileUrls) {
      // 如果 fileUrls 已经包含完整的 URL，则去除基础路径部分
      if (fileUrls && fileUrls.includes(this.$base.url)) {
        this.form.tupian = fileUrls.replace(this.$base.url, '');
      } else {
        this.form.tupian = fileUrls;
      }
    },
    HdialogVisible () {
      this.dialogVisible = true
    },  

    // 修改表单提交方法中的重置逻辑
    submitForm() {
      this.$refs.form.validate(valid => {
        if(valid) {
          const storedShangjiaId = localStorage.getItem('shangjiaId')
          // 修改数据结构，使用正确的字段名
          const data = {
            [this.nameField]: this.form.name,  // 使用动态字段名，如 bijibenming
            jiage: this.form.jiage,
            tupian: this.form.tupian,
            shangjia_id: storedShangjiaId
          }
          
          this.$http.post(`/${this.type}/add`, data).then(({data: res}) => {
            if(res && res.code === 0) {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
              // 重置表单和文件列表
              this.$nextTick(() => {
                this.$refs.form.resetFields()
                this.fileList = []
                this.form.tupian = ''
              })
            } else {
              this.$message.error(res.msg || '添加失败')
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.product-list {
  padding: 20px 0;
}
.operation-bar {
  margin-bottom: 20px;
}
.product-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}
.upload-demo {
  width: 360px;
}
.preview {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
.preview-img {
  width: 148px;
  height: 148px;
  object-fit: cover;
  border-radius: 6px;
}
.upload-demo .el-upload--picture-card {
  width: 148px;
  height: 148px;
  line-height: 148px;
}
.upload-img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

</style>